<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Models\Record;
use App\Models\Sku;
use Carbon\Carbon;
use Illuminate\Http\Request;

class HomeController extends Controller
{

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('index');
    }

    public function statistics()
    {
        $canteen_id = auth()->user()->canteen->id;
        $start_date = Carbon::now()->startOfMonth();

        $sku_count = Sku::where('canteen_id', $canteen_id)
            ->where('quantity', '>', 0)->count();

        $record_in_count = Record::where('type', Record::TYPE_IN)
            ->whereHas('sku', function ($query) use ($canteen_id) {
                $query->where('canteen_id', $canteen_id);
            })->whereDate('created_at', '>=', $start_date)->count();

        $records_in = Record::where('type', Record::TYPE_IN)
            ->whereHas('sku', function ($query) use ($canteen_id) {
                $query->where('canteen_id', $canteen_id);
            })->whereDate('created_at', '>=', $start_date)->get();

        $record_in_price = 0;
        foreach ($records_in as $record){
            $record_in_price += $record->price * $record->quantity;
        }

        $record_in_price = number_format($record_in_price / 100, 2);


        $record_out_count = Record::where('type', Record::TYPE_OUT)
            ->whereHas('sku', function ($query) use ($canteen_id) {
                $query->where('canteen_id', $canteen_id);
            })->whereDate('created_at', '>=', $start_date)->count();

        return $this->success('', compact('sku_count', 'record_in_count', 'record_in_price', 'record_out_count'));

    }


}
